<!--
 * @Author: sjt
 * @Date: 2022-10-25 13:18:12
 * @LastEditors: sjt
 * @LastEditTime: 2024-05-26 11:26:21
 * @Description: file content
-->
<template>
  <!-- <div class="text">
    <span class="num">{{ totals }}</span>
    <span class="tips">总库存（套）</span>
  </div> -->
  <div class="cir3dChart" ref="cir3dChartRef"></div>
</template>

<script setup>
import { defineExpose, ref } from 'vue'
import * as echarts from 'echarts'
import 'echarts-gl'
let charts = null
const cir3dChartRef = ref(null)
let totals = ref(0)
const initChart = (datas, t) => {
  const viewWidth = window.screen.width
  // totals.value = datas.map((item) => Number(item.value)).reduce((r, c) => r + c)
  totals.value = t
  const lengendData = datas.map((item) => item.name)
  let colors = ['#028BFF','#0DBE90', '#D65349',  '#FDC251' ]
  let optionsData = datas.map((item, index) => {
    return {
      name: item.name,
      value: item.value,
      itemStyle: {
        opacity: 0.8,
        color: colors[index]
      }
    }
  })
  function getParametricEquation(
    startRatio,
    endRatio,
    isSelected,
    isHovered,
    k,
    height
  ) {
    // 计算
    let midRatio = (startRatio + endRatio) / 2

    let startRadian = startRatio * Math.PI * 2
    let endRadian = endRatio * Math.PI * 2
    let midRadian = midRatio * Math.PI * 2

    // 如果只有一个扇形，则不实现选中效果。
    if (startRatio === 0 && endRatio === 1) {
      isSelected = false
    }

    // 通过扇形内径/外径的值，换算出辅助参数 k（默认值 1/3）
    k = typeof k !== 'undefined' ? k : 1 / 3

    // 计算选中效果分别在 x 轴、y 轴方向上的位移（未选中，则位移均为 0）
    let offsetX = isSelected ? Math.cos(midRadian) * 0.1 : 0
    let offsetY = isSelected ? Math.sin(midRadian) * 0.1 : 0

    // 计算高亮效果的放大比例（未高亮，则比例为 1）
    let hoverRate = isHovered ? 1.05 : 1

    // 返回曲面参数方程
    return {
      u: {
        min: -Math.PI,
        max: Math.PI * 3,
        step: Math.PI / 32
      },

      v: {
        min: 0,
        max: Math.PI * 0.7,
        step: Math.PI / 30
      },

      x: function (u, v) {
        if (u < startRadian) {
          return (
            offsetX + Math.cos(startRadian) * (1 + Math.cos(v) * k) * hoverRate
          )
        }
        if (u > endRadian) {
          return (
            offsetX + Math.cos(endRadian) * (1 + Math.cos(v) * k) * hoverRate
          )
        }
        return offsetX + Math.cos(u) * (1 + Math.cos(v) * k) * hoverRate
      },

      y: function (u, v) {
        if (u < startRadian) {
          return (
            offsetY + Math.sin(startRadian) * (1 + Math.cos(v) * k) * hoverRate
          )
        }
        if (u > endRadian) {
          return (
            offsetY + Math.sin(endRadian) * (1 + Math.cos(v) * k) * hoverRate
          )
        }
        return offsetY + Math.sin(u) * (1 + Math.cos(v) * k) * hoverRate
      },

      z: function (u, v) {
        if (u < -Math.PI * 1.5) {
          return Math.sin(u)
        }
        if (u > Math.PI * 2.5) {
          return Math.sin(u)
        }
        return Math.sin(v) > 0 ?  height * 0.1 > 100 ?  height * 0.004 :  height * 0.04  : -12
      }
    }
  }

  // 生成模拟 3D 饼图的配置项
  function getPie3D(pieData, internalDiameterRatio) {
    let series = []
    let sumValue = 0
    let startValue = 0
    let endValue = 0
    let legendData = []
    let k =
      typeof internalDiameterRatio !== 'undefined'
        ? (1 - internalDiameterRatio) / (1 + internalDiameterRatio)
        : 1 / 3

    // 为每一个饼图数据，生成一个 series-surface 配置
    for (let i = 0; i < pieData.length; i++) {
      sumValue += pieData[i].value

      let seriesItem = {
        name:
          typeof pieData[i].name === 'undefined'
            ? `series${i}`
            : pieData[i].name,
        type: 'surface',

        parametric: true,
        wireframe: {
          show: false
        },
        pieData: pieData[i],
        pieStatus: {
          selected: false,
          hovered: false,
          k: 1 / 10
        }
      }

      if (typeof pieData[i].itemStyle != 'undefined') {
        let itemStyle = {}

        typeof pieData[i].itemStyle.color != 'undefined'
          ? (itemStyle.color = pieData[i].itemStyle.color)
          : null
        typeof pieData[i].itemStyle.opacity != 'undefined'
          ? (itemStyle.opacity = pieData[i].itemStyle.opacity)
          : null

        seriesItem.itemStyle = itemStyle
      }

      series.push(seriesItem)
    }

    // 使用上一次遍历时，计算出的数据和 sumValue，调用 getParametricEquation 函数，
    // 向每个 series-surface 传入不同的参数方程 series-surface.parametricEquation，也就是实现每一个扇形。
    for (let i = 0; i < series.length; i++) {
      endValue = startValue + series[i].pieData.value

      series[i].pieData.startRatio = startValue / sumValue
      series[i].pieData.endRatio = endValue / sumValue
      series[i].parametricEquation = getParametricEquation(
        series[i].pieData.startRatio,
        series[i].pieData.endRatio,
        false,
        false,
        k,
        series[i].pieData.value
      )

      startValue = endValue

      legendData.push(series[i].name)
    }

    return series
  }
  // 传入数据生成 option
  // const optionsData = [
  //   {
  //     name: '60天以上',
  //     value: 70,
  //     itemStyle: {
  //       opacity: 0.8,
  //       color: '#D65349'
  //     }
  //   },

  //   {
  //     name: '30天以上',
  //     value: 50,
  //     itemStyle: {
  //       opacity: 0.8,
  //       color: '#0DBE90'
  //     }
  //   },
  //   {
  //     name: '15天以上',
  //     value: 30,
  //     itemStyle: {
  //       opacity: 0.8,
  //       color: '#028BFF'
  //     }
  //   },
  //   {
  //     name: '15天以内',
  //     value: 30,
  //     itemStyle: {
  //       opacity: 0.8,
  //       color: '#FDC251'
  //     }
  //   }
  // ]

  const series = getPie3D(optionsData, 0.6)

  // 准备待返回的配置项，把准备好的 legendData、series 传入。

  let total = optionsData.reduce(function (prev, cur, index, arr) {
    return prev + cur.value
  }, 0) //数据总和
  let option = {

    legend: {
      // icon: `path://M881.387 297.813c38.08 65.387 57.28 136.747 57.28 214.187s-19.094 148.8-57.28 214.187c-38.187 65.28-89.92 117.12-155.2 155.2S589.44 938.667 512 938.667s-148.8-19.094-214.187-57.28c-65.28-38.08-117.013-89.814-155.306-155.307C104.427 660.8 85.333 589.44 85.333 512c0-77.333 19.094-148.693 57.28-214.187 38.08-65.28 89.814-117.013 155.307-155.306C363.2 104.533 434.56 85.333 512 85.333c77.333 0 148.693 19.094 214.187 57.28 65.28 38.187 117.013 89.92 155.2 155.2z m-217.707-47.36C617.387 223.467 566.827 209.92 512 209.92s-105.387 13.547-151.68 40.533-82.987 63.68-109.973 109.974c-26.987 46.293-40.534 96.853-40.534 151.68s13.547 105.386 40.534 151.68c26.986 46.293 63.68 82.986 109.973 109.973 46.293 26.987 96.853 40.533 151.68 40.533s105.387-13.546 151.68-40.533c46.293-26.987 82.987-63.68 109.973-109.973 26.987-46.294 40.534-96.854 40.534-151.68s-13.547-105.387-40.534-151.68c-27.093-46.294-63.786-82.987-109.973-109.974z`,
      icon: 'circle',
      data: lengendData,
      orient: 'vertical',
      top: 'center',
      right: '4%',
      itemGap: 16,
      itemWidth: 8,
      itemHeight: 8,
      textStyle: {
        rich: {
          name: {
            width: 85,
            fontSize: 12,
            color: '#fff'
          },
          value: {
            width: 35,
            align: 'right',
            fontFamily: 'Medium',
            fontSize: 12,
            color: '#fff'
          }
        }
      },
      formatter: (name) => {
        for (let i = 0; i < datas.length; i++) {
          if (name == datas[i].name) {
            return `{name|${name}}{value|${datas[i].value}件}`
          }
        }
      }
    },
    animation: true,
    tooltip: {
      show: false,
      backgroundColor: 'transparent', // 修改背景颜色
      borderColor: 'transparent', // 修改边框颜色
      borderWidth: 0,
      padding: 0,
      formatter: (params) => {
        if (
          params.seriesName !== 'mouseoutSeries' &&
          params.seriesName !== 'pie2d'
        ) {
          return `<div class="tool" >
                <div class="name">${params.seriesName}</div>
                <div class="num">${
                  option.series[params.seriesIndex].pieData.value
                }吨(<span>${
            (option.series[params.seriesIndex].pieData.value / total) * 100
          }%</span>)</div>
              </div>`
          //							return `${params.seriesName}<br/>
          //      <span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${params.color};"></span>
          //      ${option.series[params.seriesIndex].pieData.value + '吨'}${'(' + (option.series[params.seriesIndex].pieData.value/total)*100 + '%)'}`;
        }
      },
      textStyle: {
        fontSize: 12
      }
    },
    labelLine: {
      show: false,
      lineStyle: {
        color: '#7BC0CB'
      }
    },
    label: {
      show: false,
      position: 'outside',
      formatter: '{d}%',
      color: 'inherit'
    },
    xAxis3D: {
      min: -1,
      max: 1
    },
    yAxis3D: {
      min: -1,
      max: 1
    },
    zAxis3D: {
      min: -1,
      max: 1
    },
    grid3D: {
      show: false,
      boxHeight: 1,
      top: '-16%',
      left: '-21%',
      scale: 1,
      viewControl: {
        rotateSensitivity: 1,
        zoomSensitivity: 0,
        distance: viewWidth <= 2560 ? 135 : 152,
        alpha: 25,
        beta: 110
        // autoRotate: true, // 自动旋转
      }
    },

    series: series
  }

  if (!charts) {
    charts = echarts.init(cir3dChartRef.value)
    charts.setOption(option)
  } else {
    charts.dispose()
    charts = echarts.init(cir3dChartRef.value)
    charts.setOption(option)
  }
  window.addEventListener('resize', () => {
    if (charts) {
      charts.resize()
    }
  })
}

defineExpose({
  initChart
})
</script>

<style lang="scss" scoped>
.cir3dChart {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background: url('@/assets/images/page2/ltbt.png') no-repeat;
  background-size: 55% 105%;
  background-position: 2% center;
}
.text {
  position: absolute;
  top: 5%;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  z-index: 2;
  pointer-events: null;
  .num {
    margin-right: 15px;
    font-family: DIN;
    font-weight: bold;
    font-size: 52px;
    color: #ffffff;
    text-shadow: 0 0 14px rgba(2, 139, 255, 0.56),
      0 0 14px rgba(2, 139, 255, 0.56);
  }
  .tips {
    font-family: Source Han Sans CN;
    font-weight: 400;
    font-size: 18px;
    color: #c7dffc;
    line-height: 23px;
  }
}
</style>
